package com.itheima.rocketmq.rocketmqdemo.base.product;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.TimeUnit;

/**
 * 发送异步消息：时间敏感
 * @description:
 * @author: ycc
 * @time: 2021/3/24
 */
public class AsyncProduct {
    public static void main(String[] args) throws Exception {
//        1.创建消息生产者producer，并制定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("group2");
//        2.指定Nameserver地址
        producer.setNamesrvAddr("127.0.0.1:9876;127.0.0.1:9877");
//        3.启动producer
        producer.start();
        producer.setRetryTimesWhenSendAsyncFailed(1);
        for (int i=0;i<10;i++){
            final int index = i;
//        4.创建消息对象，指定主题Topic、Tag和消息体
            Message msg = new Message("base2","Tag2","key2",("余长城异步"+i).getBytes());
//        5.发送消息
            producer.send(msg, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println(sendResult+"---发送成功---"+index);
                }

                @Override
                public void onException(Throwable e) {
                    System.out.println(index+"----发送失败-----"+e);
                    e.printStackTrace();
                }

            },1000*30);
            TimeUnit.SECONDS.sleep(1);
        }
//        6.关闭生产者producer
        producer.shutdown();
    }
}


